<template>
  <view class="chat">
    <!-- 聊天主体 -->
    <scroll-view
      :style="{ height: `${windowHeight - keyboardHeight + 350}rpx` }"
      id="scrollview"
      scroll-y="true"
      :scroll-top="scrollTop"
      class="scroll-view"
    >
      <!-- 聊天记录 -->
      <view id="msglistview" class="chat-body">
        <!-- 聊天记录 -->
        <view v-for="(item, index) in msgList" :key="index">
          <!-- 自己发的消息 -->
          <view class="item self" v-if="item.userContent || item.userImage">
            <!-- 图片内容 -->
            <image
              class="content right img-content"
              v-if="item.userImage"
              :src="item.userImage"
              mode="widthFix"
            ></image>
            <!-- 文字内容 -->
            <view class="content right text-content" v-if="item.userContent">
              {{ item.userContent }}
            </view>
            <!-- 头像 -->
            <image class="avatar" :src="item.image"></image>
          </view>

          <!-- 机器人发的消息 -->
          <view class="item Ai" v-if="item.botContent || item.botImage || item.foodInfo">
            <!-- 头像 -->
            <image class="avatar" :src="item.image"></image>
            <!-- 图片内容 -->
            <image
              class="content left img-content"
              v-if="item.botImage"
              :src="item.botImage"
              mode="widthFix"
            ></image>
            <!-- 文字内容 -->
            <view class="content left text-content" v-if="item.botContent">
              {{ item.botContent }}
            </view>
            <!-- 食物识别结果 -->
            <view class="content left food-info" v-if="item.foodInfo">
              <text>识别到的食物：{{ item.foodInfo.foodName }}</text>
              <text>重量：{{ item.foodInfo.weight }}</text>
              <text>热量：{{ item.foodInfo.calories }}</text>
            </view>
          </view>
        </view>

        <!-- 加载指示器 -->
        <div v-if="isloading">
          <uni-load-more color="#007AFF" iconType="circle" :status="loading" />
        </div>
      </view>
    </scroll-view>

    <!-- 底部消息发送栏 -->
    <view class="chat-bottom" :style="{ height: `${bottomHeight - 20}rpx` }">
      <view class="send-msg" :style="{ bottom: `${keyboardHeight + 50}rpx` }">
        <!-- 上传图片按钮容器 -->
        <view class="upload-btn-container">
          <button :disabled="isloading" @click="uploadImage" class="upload-btn">上传图片</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      windowHeight: 0, // 窗口高度
      keyboardHeight: 0, // 键盘高度
      bottomHeight: 0, // 底部高度
      scrollTop: 0, // 滚动位置
      msgList: [], // 消息列表
      isloading: false, // 是否正在加载
      loading: 'loading', // 加载状态
      user_mode: false, // 用户模式
      error: null, // 错误信息
    };
  },
  methods: {
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('#scrollview').boundingClientRect((data) => {
          this.scrollTop = data.height;
        }).exec();
      });
    },
    // 图片上传方法
    uploadImage() {
      uni.chooseImage({
        count: 1, // 只能选择一张图片
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album'], // 仅从相册选择图片
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          // 添加用户上传的图片到消息列表
          let obj = {
            botContent: '',
            userContent: '',
            userImage: tempFilePaths[0],
            image: '/static/userAvatar.svg',
          };
          this.msgList.push(obj);
          this.scrollToBottom();

          // 发送图片给服务器进行处理
          this.isloading = true;
          uni.uploadFile({
            url: `${this.$baseUrl}/recognize-food/`, // 后端接口地址
            filePath: tempFilePaths[0],
            name: 'file',
            success: (uploadRes) => {
              if (uploadRes.statusCode === 200) {
                console.log('成功获取到数据！');
                let response = JSON.parse(uploadRes.data);

                // 添加机器人回复的消息到消息列表
                let botObj = {
                  foodInfo: {
                    foodName: response.food_name || '未知食物',
                    weight: response.weight || '未知重量',
                    calories: response.calories || '未知热量',
                  },
                  userContent: '',
                  image: '/static/aiAvatar.svg',
                };
                if (this.user_mode) {
                  botObj.image = '/static/aiAvatarPlus.svg';
                }
                this.msgList.push(botObj);
                this.scrollToBottom();
              } else {
                this.error = '获取数据失败，请重试！';
                uni.showToast({
                  title: '请求失败，请重试',
                  icon: 'none',
                });
              }
            },
            fail: (err) => {
              console.log('请求失败！');
              this.error = err.errMsg;
              uni.showToast({
                title: '上传失败，请检查文件格式',
                icon: 'none',
              });
            },
            complete: () => {
              console.log('请求完成！');
              this.isloading = false;
            },
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.chat {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.scroll-view {
  flex: 1;
  overflow-y: auto;
}

.chat-body {
  padding: 20rpx;
}

.item {
  display: flex;
  margin-bottom: 20rpx;
}

.item.self {
  justify-content: flex-end;
}

.item.Ai {
  justify-content: flex-start;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.content {
  max-width: 60%;
  margin: 0 20rpx;
}

.content.left {
  background-color: #f0f0f0;
}

.content.right {
  background-color: #007aff;
  color: #fff;
}

.text-content {
  padding: 16rpx;
  border-radius: 8rpx;
}

.img-content {
  max-width: 60%;
  border-radius: 8rpx;
}

.food-info {
  padding: 16rpx;
  margin: 16rpx;
  border-radius: 8rpx;
  background-color: #f0f0f0;
  font-size: 28rpx;
  font-family: PingFang SC;
  font-weight: 500;
  color: #333333;
  line-height: 36rpx;
	text{
  	  margin-right: 20rpx;
	}
}

/* 上传图片按钮容器 */
.upload-btn-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  width: 100%;
}

/* 上传图片按钮样式 */
.upload-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200rpx; /* 调整按钮宽度 */
  height: 75rpx;
  background: #ed5a65;
  border-radius: 50rpx;
  font-size: 28rpx;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ffffff;
  line-height: 28rpx;
  margin: 0 auto; /* 确保按钮在容器内居中 */
}
</style>